package com.blb.demo4;

import java.lang.reflect.Field;

/**
 * @author lvtian
 * @date 2022/12/23 9:40
 */
public class MyAnnotationBeanFactory {
    public <T> T getBean(Class<T> tClass){
        try {
            //实例化对象
            T obj = tClass.newInstance();
            //获得所有属性
            Field[] fields = tClass.getDeclaredFields();
            //读取属性上的自定义注解
            for(Field field : fields){
                MyValue myValue = field.getDeclaredAnnotation(MyValue.class);
                field.setAccessible(true);
                if(myValue != null){
                    field.set(obj, myValue.value());
                }
                MyAutowite myAutowire = field.getDeclaredAnnotation(MyAutowite.class);
                if(myAutowire != null){
                    //如果是MyAutowire，需要创建配置类型的对象，使用set赋值
                    Class type = myAutowire.value();
                    Object objValue = type.newInstance();
                    field.set(obj,objValue);
                }
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
